package cn.edu.nju.ws.sview.group;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.GroupCache;
import cn.edu.nju.ws.sview.cache.MessageCache;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.util.URIUtil;
import cn.edu.nju.ws.sview.views.Group;
import cn.edu.nju.ws.sview.views.User;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing.QuadItem;
import cn.edu.nju.ws.sview.wyge.relations.adataset.CustomDataset;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relation;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relations;
import cn.edu.nju.ws.sview.wyge.relations.datasets.DatasetBrowsing;
import cn.edu.nju.ws.sview.wyge.relations.datasets.DatasetItem;

public class GroupDetailServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml;charset=utf-8");
		String result=null;
		String json = request.getParameter("msg");
//		System.out.println("msg..."+json);
		
		if(json != null){
			String data = URLDecoder.decode(json, "utf8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(data);
			String action = (String) regtJSON.get("action");
			String gname = (String) regtJSON.get("gname");
			int gid = Group.getGroupIdByName(gname);
			int sender=User.getUserIdByName((Group.getAdmin(gid)));
			if(gid<0){
				result="failed";
			}else if(action.contentEquals("getViewList")){
				try {
					Connection conn = DBConnectionFactory.getConnection();
					PreparedStatement pstmt = conn.prepareStatement("select id,name,use_times from view where group_id=? order by id");
					pstmt.setInt(1, gid);
					ResultSet rs = pstmt.executeQuery();
					StringBuffer sb = new StringBuffer();
					while(rs.next()){
						sb.append("<tr id='v"+rs.getInt(1)+"'><td>"+rs.getString(2)+"</td><td>"+rs.getInt(3)+"</td></tr>");
					}
					result = sb.toString();
					rs.close();
					pstmt.close();
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(action.contentEquals("getEntityList")){
				String lang = (String) regtJSON.get("lang");
				StringBuffer sb = new StringBuffer();
				ArrayList<QuadItem> elist = new ArrayList<EntityBrowsing.QuadItem>();
				boolean flag = EntityBrowsing.fetchGroupEntities(gid, 0, -1, lang, elist);
				if(flag){
					for(QuadItem qi : elist){
						int id = qi.getId();
						int genre = qi.getGenre();
						String genre_str = URIUtil.getItemTypeStr(genre);
						String name = qi.getName();
						sb.append("<tr id='"+genre_str+id+"'><td><a href='/sview/entity/e"+id+"'>"+name+"</a></td></tr>");
					}
				}
				result = sb.toString();
//				try {
//					Connection conn = DBConnectionFactory.getConnection();
//					PreparedStatement pstmt = conn.prepareStatement("select id,name from identity where group_id=? order by id");
//					pstmt.setInt(1, gid);
//					ResultSet rs = pstmt.executeQuery();
//					StringBuffer sb = new StringBuffer();
//					while(rs.next()){
//						sb.append("<tr id='e"+rs.getInt(1)+"'><td><a href='/sview/entity/e"+rs.getInt(1)+"'>"+rs.getString(2)+"</a></td></tr>");
//					}
//					result = sb.toString();
//					rs.close();
//					pstmt.close();
//					conn.close();
//				} catch (SQLException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
			}else if(action.contentEquals("getDatasetList")){
				String lang = (String) regtJSON.get("lang");
				ArrayList<DatasetItem> dslist = DatasetBrowsing.fetchGroupAll(gid, 0, -1);
				StringBuffer sb = new StringBuffer();
				for(DatasetItem di : dslist){
					int ds_id = di.getId();
					String name = DatasetItem.getShowNameByDatasetID(di, lang);
					sb.append("<tr id='d"+ds_id+"'><td><a href='/sview/dataset/c"+ds_id+"'>"+name+"</a></td><td>"+CustomDataset.getUpdateDateByCustomDatasetID(ds_id, "yyyy/MM/dd")+"</td></tr>");
				}
				result = sb.toString();	
//				try {
//					Connection conn = DBConnectionFactory.getConnection();
//					PreparedStatement pstmt = conn.prepareStatement("select id,name from custom_dataset where group_id=? order by id");
//					pstmt.setInt(1, gid);
//					ResultSet rs = pstmt.executeQuery();
//					StringBuffer sb = new StringBuffer();
//					while(rs.next()){
//						int ds_id = rs.getInt(1);
//						sb.append("<tr id='d"+ds_id+"'><td><a href='/sview/dataset/c"+ds_id+"'>"+rs.getString(2)+"</a></td><td>"+CustomDataset.getCreatedDateByCustomDatasetID(ds_id, "yyyy/MM/dd")+"</td></tr>");
//					}
//					result = sb.toString();
//					rs.close();
//					pstmt.close();
//					conn.close();
//				} catch (SQLException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
			}else if(action.contentEquals("getRelationList")){
//				try {
					ArrayList<Relation> array = Relations.getRelationsByGroupId(gid);
//					Connection conn = DBConnectionFactory.getConnection();
//					PreparedStatement pstmt = conn.prepareStatement("select id,name from custom_dataset where group_id=? order by id");
//					pstmt.setInt(1, gid);
//					ResultSet rs = pstmt.executeQuery();
					StringBuffer sb = new StringBuffer();
					for(Relation item : array){
						String roles = "";
						for(String role : item.getRoles()){
							roles += role + ",";
						}
						roles = roles.substring(0, roles.length()-1);
						sb.append("<tr id='r"+item.getRelationID()+"'><td>"+item.getName()+"("+roles+")"+"</td><td>"+item.getDate()+"</td></tr>");
					}
					result = sb.toString();
//					rs.close();
//					pstmt.close();
//					conn.close();
//				} catch (SQLException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
			}else if(action.contentEquals("delMem")){
				String unames = (String)regtJSON.get("unames");
				try {
//					System.out.println("in...");
					//remove members
					Connection conn = DBConnectionFactory.getConnection();
					PreparedStatement rmpstmt = conn.prepareStatement("delete from group_member where gid=? and uid=?");
					rmpstmt.setInt(1, gid);
					//msg to removed members
					PreparedStatement pstmt = conn.prepareStatement("insert into msg(title,time,sender_id,receiver_id,content) values(?,?,?,?,?)");
					String[] names = unames.split(",");
					Timestamp time = new java.sql.Timestamp(new Date().getTime());
					int memid;
					for(int i=0; i<names.length; i++){
						memid = User.getUserIdByName(names[i]);
						rmpstmt.setInt(2, memid);
						rmpstmt.execute();
							pstmt.setString(1, "Notifitation from group "+gname);
							pstmt.setTimestamp(2, time);
							pstmt.setInt(3, sender);
							pstmt.setInt(4, memid);
							pstmt.setString(5, "Dear friend,<br/>I'm sorry to tell you that you have been removed out of our <a id='gname' href='javascript:void(0)'>"+gname+"</a> group. ");
							pstmt.execute();
							MessageCache.getInstance().updateMessages(memid);
					}
//					System.out.println("notified!");
					//msg to admin
					pstmt.setString(1, "Removed member successfully");
					pstmt.setTimestamp(2, time);
					pstmt.setInt(3, 0);
					pstmt.setInt(4, sender);
					pstmt.setString(5, "&nbsp;&nbsp;&nbsp;&nbsp;Dear user,<br/>&nbsp;&nbsp;&nbsp;&nbsp;You have removed user(s) <b>"+unames+"</b> out of group <b>"+gname+"</b> successfully.");
					pstmt.execute();
//					System.out.println("successed!");
					pstmt.close();
					conn.close();
					MessageCache.getInstance().updateMessages(sender);
					result = "success";
				} catch (SQLException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(action.contentEquals("memLeave")){
				String unames = (String)regtJSON.get("unames");
				try {
//					System.out.println("in...");
					//remove members
					Connection conn = DBConnectionFactory.getConnection();
					PreparedStatement rmpstmt = conn.prepareStatement("delete from group_member where gid=? and uid=?");
					rmpstmt.setInt(1, gid);
					//msg to removed members
					PreparedStatement pstmt = conn.prepareStatement("insert into msg(title,time,sender_id,receiver_id,content) values(?,?,?,?,?)");
					String[] names = unames.split(",");
					Timestamp time = new java.sql.Timestamp(new Date().getTime());
					int memid = User.getUserIdByName(names[0]);;
					rmpstmt.setInt(2, memid);
					rmpstmt.execute();
					GroupCache.getInstance().updateGroupIDs(memid);
						pstmt.setString(1, "Notifitation from group "+gname);
						pstmt.setTimestamp(2, time);
						pstmt.setInt(3, 0);
						pstmt.setInt(4, sender);
						pstmt.setString(5, "Dear adminstrator,<br/>User <b>"+unames+"</b> has left our <a id='gname' href='javascript:void(0)'>"+gname+"</a> group. ");
						pstmt.execute();
//					System.out.println("notified!");
					//msg to admin
					pstmt.setString(1, "Removed member successfully");
					pstmt.setTimestamp(2, time);
					pstmt.setInt(3, 0);
					pstmt.setInt(4, memid);
					pstmt.setString(5, "&nbsp;&nbsp;&nbsp;&nbsp;Dear user,<br/>&nbsp;&nbsp;&nbsp;&nbsp;You have left group <b>"+gname+"</b> successfully.");
					pstmt.execute();
//					System.out.println("successed!");
					pstmt.close();
					conn.close();
					MessageCache.getInstance().updateMessages(sender);
					MessageCache.getInstance().updateMessages(memid);
					result = "success";
				} catch (SQLException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}//end of if_json
		
//		System.out.println("result:"+result+"\tlength:"+result.length());
		response.getWriter().print(result);
	}
}
